#pragma once
#ifndef myIEventManager_h__
#define myIEventManager_h__

#include "../inc/sky.h"
#include "./myMessage.h"


namespace Sky
{
	class Timer;
}
namespace Framework
{
	using namespace Sky;
	
	class myEventSender;
	class myEvent;
	
	class myEventManager;
	class myApplication;
	
	typedef TResult  (*EventCalledProc)(myEventManager* ,Message* );
	
	class myEventManager : private TreeNode
	{
	
	public:
		myEventManager();
		~myEventManager();
		virtual MsgStatus	handlePostEvent(Message* msg){m_EventQueue.in(msg);return vContinue;};
	
		virtual MsgStatus 	handleSendEvent(Message* msg){return vContinue;};
		//
		virtual TBool	getQueuedMessage(Message* msg);
		Timer* 	getTimer();
		TVoid handleTimer()
		{
			CBList::iterator itr;
			const CallbackNode* node;
			CallbackNode* pNode;
			for(itr = _list.getHead(); itr != vNull; ++itr)
			{
				node = itr;
				pNode = const_cast<CallbackNode*>(node);
				pNode->_left = 0;
				if(pNode->_left == 0)
				{
					(pNode->_cb)(this,vNull);
					if(pNode->_bRepeat)
						pNode->_left = pNode->_interal;
					else
						_list.remove(itr);
				}
			}
		}
		TBool	createTimer(Handler::Handle cb,TUint internal,TBool bRepeat = vTrue)
		{
			getTimer();
			CallbackNode node;
			node._bRepeat = bRepeat;
			node._cb = cb;
			node._interal = internal;
			node._left = internal;
			_list.append(node);
		}
		TVoid   deleteTimer(Handler::Handle cb)
		{
			CBList::iterator itr;
			const CallbackNode* node;
			CallbackNode* pNode;
			for(itr = _list.getHead(); itr != vNull;)
			{
				node = itr;
				pNode = const_cast<CallbackNode*>(node);
				if(pNode->_cb == cb)
				{
					_list.remove(itr);
				}
			}
		}
		NType::TVoid			setEventCallBack(Handler::Handle proc){m_CallBack = proc;}
		virtual myApplication*	getApplication(){return m_app;};
		TResult myEventManager::dispatchSendEvent( Message* msg );
		TBool myEventManager::Create( myApplication* app );
		MsgStatus	callSystem(Message* message)
		{
			return m_CallBack(this,message);
		}
	protected:
		Handler::Handle 		m_CallBack;
		myApplication*  		m_app;
		FifoQueue<MessagePtr,10>	m_EventQueue;
		typedef struct _CallbackNode_
		{
			Handler::Handle _cb;
			TUint _interal;
			TUint _left;
			TBool _bRepeat;
		}CallbackNode;
		typedef List<CallbackNode> CBList;
		CBList _list;
		Timer* m_Timer;
	};
}

#endif // myIEventManager_h__
